#include"Comm.hpp"
#include<sys/wait.h>

//void GetMessage(int fd)
static void GetMessage(int fd)      //此函数不会改变，可将其声明为静态
{
    char buff[SIZE];      //类型为char而不是char*，否则下方的输出操作将会出错
    while(true)
    {
        memset(buff, '\0', sizeof(buff));
        ssize_t sz = read(fd, buff, sizeof(buff) - 1);
        if(sz > 0)
        {
            cout << "[" << getpid() << "]" << "Client say: " << buff << endl;
            //cout<<buff<<endl;
        }
        else if(sz == 0)
        {
            cout << "[" << getpid() << "]" << "write quit, i quit" << endl;
            break;
        }
        else
        {
            Log("read error", Error) << endl;
            //exit(1);
            break;      //退出循环即可，在main函数中再统一调用exit函数
        }
    }
}

int main()
{
    //int ret = mkfifo(PATH_NAME, MODE);
    int ret = mkfifo(PATH_NAME.c_str(), MODE);      //将PATH_NAME修改为string对象后，这些操作也需要跟着改
    assert(ret != -1);
    Log("make nameed pipe file success", Debug) << endl;
    //sleep(3);

    //int fd = open(PATH_NAME, O_RDONLY);
    int fd = open(PATH_NAME.c_str(), O_RDONLY);
    assert(ret != -1);
    Log("open file success", Debug) << endl;
    //sleep(3);
    
    int nums = 3;       //方便修改
    //for(int i = 0; i < 3; ++i)
    for(int i = 0; i < nums; ++i)
    {
        //int n  = fork();
        pid_t n  = fork();
        assert(n != -1);
        if(n == 0)
        {
            GetMessage(fd);
            exit(2);        //直接让子进程退出，不再执行下方的内容
        }
    }

    //for(int i = 0; i < 3; ++i)
    for(int i = 0; i < nums; ++i)
    {
        ret = waitpid(-1, nullptr, 0);
        assert(ret != -1);
    }
    Log("wait children process success", Debug) << endl;
    //sleep(3);
    close(fd);

    ret = unlink(PATH_NAME.c_str());
    assert(ret != -1);
    Log("unlink named pipe file success", Debug) << endl;

    return 0;
}